package crypto;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Checksum {

  public static void main(String[] args) throws NoSuchAlgorithmException,
      IOException {
    if (args.length == 0 || args.length > 2)
      Crypt
          .error("Checksum [-md2|-md5|-sha-1|-sha-256|-sha-384|-sha-512] file");
    String algorithm = null;
    if (args.length == 2) {
      String alg = args[0].toLowerCase();
      if ("-md2".equals(alg))
        algorithm = "md2";
      if ("-md5".equals(alg))
        algorithm = "md5";
      if ("-sha-1".equals(alg))
        algorithm = "sha-1";
      if ("-sha-256".equals(alg))
        algorithm = "sha-256";
      if ("-sha-384".equals(alg))
        algorithm = "sha-384";
      if ("-sha-512".equals(alg))
        algorithm = "sha-512";
    } else
      algorithm = "md5";
    if (algorithm == null)
      Crypt.error("Unbekannter algorithmus.");
    String filename = args[args.length - 1];
    File file = new File(filename);
    if (!file.exists())
      Crypt.error("Datei existiert nicht");
    MessageDigest md = MessageDigest.getInstance(algorithm);
    FileInputStream fileIn = new FileInputStream(file);
    DigestInputStream digestIn = new DigestInputStream(fileIn, md);
    byte[] buffer = new byte[4096];
    long count = 0;
    int read;
    while ((read = digestIn.read(buffer)) != -1) {
      count+=read;
    }
    byte[] digest = md.digest();
    System.out.println("length : " + count);
    System.out.print(algorithm);
    System.out.print(": ");
    for (byte b: digest)
      System.out.print(Integer.toString(b&0xff, 16));
  }
}